package com.ts.proj.controller;

import com.alibaba.fastjson.JSONArray;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.proj.entity.SystemColumnEntity;
import com.ts.proj.entity.SystemConstantEntity;
import com.ts.proj.entity.SystemFieldEntity;
import com.ts.proj.entity.SystemGlobalEntity;
import com.ts.proj.service.*;
import com.ts.util.JurisdictionUtil;
import com.ts.util.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@Slf4j
public class SystemConfigController extends BaseController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SystemColumnService systemColumnService;

    @Autowired
    private SystemGlobalService systemGlobalService;

    @Autowired
    private SystemFieldService systemFieldService;

    @Autowired
    private SystemConstantService systemConstantService;

    /**
     * 常量维护
     * @return
     */
    @RequestMapping("/config-develop-list")
    public ModelAndView constantListManage(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            viewName = "config/config-develop-list";
            Object attribute = this.getRequest().getSession().getAttribute(ConsoleConstant.BTNRIGHTS);
            List<PageData> buttonList = (List<PageData>) JSONArray.parse(attribute.toString());
            modelAndView.addObject("buttons", buttonList);
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    /**
     * 列头配置
     * @return
     */
    @RequestMapping("/config-column-manage")
    public ModelAndView columnConfigManage(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            viewName = "config/config-column-manage";
            Object attribute = this.getRequest().getSession().getAttribute(ConsoleConstant.BTNRIGHTS);
            List<PageData> buttonList = (List<PageData>) JSONArray.parse(attribute.toString());
            modelAndView.addObject("buttons", buttonList);
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    @RequestMapping("/column-add/{id}")
    public ModelAndView columnAdd(@PathVariable("id") String id){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            SystemColumnEntity byId = systemColumnService.findById(Integer.valueOf(id));
            modelAndView.addObject("entity", byId);
            List<String> allTables = systemColumnService.findAllTables();
            modelAndView.addObject("list", allTables);
            viewName = "config/column-add";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    @RequestMapping("/column-set/{id}")
    public ModelAndView columnSet(@PathVariable("id") String id) {
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            SystemColumnEntity byId = systemColumnService.findById(Integer.valueOf(id));
            String[] split = byId.getAllName().split(" ");
            List<String> splitFreezeList = null;
            List<String> splitHiddenList = null;
            try{
                splitFreezeList = Arrays.asList(byId.getFreezeName().split(" "));
                splitHiddenList = Arrays.asList(byId.getHiddenName().split(" "));
            }catch (NullPointerException e){

            }
//            int columnNumber = 2;
            int columnNumber = 1;
            int size = split.length % columnNumber == 0 ? split.length / columnNumber : (split.length / columnNumber + 1);
            StringBuffer columnsSB = new StringBuffer();
            //获取说明
            PageData fields = new PageData();
            fields.put("tableName", byId.getClassName());
            List<SystemFieldEntity> all = systemFieldService.findAll(fields);

            PageData constantPd = new PageData();
            constantPd.put("constantKey", "constraint-types");
            List<SystemConstantEntity> constantsList = systemConstantService.findAll(constantPd);
            constantPd.put("constantKey", "formatter-types");
            List<SystemConstantEntity> formatterList = systemConstantService.findAll(constantPd);

            int index = 0;
            for(int i=0;i<size;i++){
                columnsSB.append("<tr class=\"text-c\">");
                for(int j=0;j<columnNumber;j++){
//                    index = i * 2 + j;
                    index = i;
                    if(index<split.length){
                        columnsSB.append(" <th>"+split[index]+"</th>");
                        //列名
                        columnsSB.append(" <td><div class=\"formControls\"> <input type=\"text\" class=\"input-text\" value=\""+getCN(all,split[index])+"\" placeholder=\"\" id=\""+split[index]+"_desc"+"\" name=\""+split[index]+"_desc"+"\"> </div></td>");
                        //
                        columnsSB.append("  <td><div class=\"formControls skin-minimal\">");
                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"\" name=\""+split[index]+"\" ");
                        if(null!=splitFreezeList&&splitFreezeList.contains(split[index])){
                            columnsSB.append("checked=\"checked\"");
                        }
                        columnsSB.append("></div>");
                        columnsSB.append("</div></td>");

                        //是否导出
                        columnsSB.append("  <td><div class=\"formControls skin-minimal\">");
                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"_export\" name=\""+split[index]+"_export\" ");
                        if(getExport(all,split[index]).equals("Y")){
                            columnsSB.append("checked=\"checked\"");
                        }
                        columnsSB.append("></div>");
                        columnsSB.append("</div></td>");
                        //是否单元格合并
                        columnsSB.append("  <td><div class=\"formControls skin-minimal\">");
                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"_merge\" name=\""+split[index]+"_merge\" ");
                        if(getMerge(all,split[index]).equals("Y")){
                            columnsSB.append("checked=\"checked\"");
                        }
                        columnsSB.append("></div>");
                        columnsSB.append("</div></td>");

                        //是否隐藏
                        columnsSB.append("<td><div class=\"formControls skin-minimal\">");
                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"_display"+"\" name=\""+split[index]+"_display"+"\"");
                        if(null!=splitHiddenList&&splitHiddenList.contains(split[index])){
                            columnsSB.append("checked=\"checked\"");
                        }
                        columnsSB.append("></div>");
                        columnsSB.append(" </div></td>");

                        //是否Format
                        columnsSB.append(" <td><div class=\"formControls\"><span class=\"select-box\"><select id=\""+split[index]+"_format\" name=\""+split[index]+"_format\" class=\"select\">");
                        for(int n=0;n<formatterList.size();n++){
                            columnsSB.append("<option value=\""+formatterList.get(n).getConstantValue()+"\"");
                            if(getTypeFormatter(all,split[index]).equals(formatterList.get(n).getConstantValue())){
                                columnsSB.append(" selected ");
                            }
                            columnsSB.append(">"+formatterList.get(n).getConstantValueDesc()+"</option>");
                        }
                        columnsSB.append("  </select></span></div></td>");

                        //约束类型
                        columnsSB.append(" <td><div class=\"formControls\"><span class=\"select-box\"><select id=\""+split[index]+"_typeConstraint\" name=\""+split[index]+"_typeConstraint\" class=\"select\">");
                        for(int m=0;m<constantsList.size();m++){
                            columnsSB.append("<option value=\""+constantsList.get(m).getConstantValue()+"\"");
                            if(getTypeConstraint(all,split[index]).equals(constantsList.get(m).getConstantValue())){
                                columnsSB.append(" selected ");
                            }
                            columnsSB.append(">"+constantsList.get(m).getConstantValueDesc()+"</option>");
                        }
                        columnsSB.append("</select></span></div></td>");
                    }else if(index==split.length){
                        columnsSB.append(" <th> </th><td><div class=\"formControls\"></div></td><td><div class=\"formControls\"></div></td>");
                        columnsSB.append(" <td><div class=\"formControls\"></div></td><td></td><td><div class=\"formControls\"></div></td>");
                    }
//                    if(index<split.length){
//                        columnsSB.append(" <th>"+split[index]+"</th>");
//                        columnsSB.append(" <td><div class=\"formControls\"> <input type=\"text\" class=\"input-text\" value=\""+getCN(all,split[index])+"\" placeholder=\"\" id=\""+split[index]+"_desc"+"\" name=\""+split[index]+"_desc"+"\"> </div></td>");
//                        columnsSB.append("  <td><div class=\"formControls skin-minimal\">");
//                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"\" name=\""+split[index]+"\" ");
//                        if(null!=splitFreezeList&&splitFreezeList.contains(split[index])){
//                            columnsSB.append("checked=\"checked\"");
//                        }
//                        columnsSB.append("></div>");
//                        columnsSB.append("</div></td>");
//                        columnsSB.append("<td><div class=\"formControls skin-minimal\">");
//                        columnsSB.append(" <div class=\"check-box\"><input type=\"checkbox\" id=\""+split[index]+"_display"+"\" name=\""+split[index]+"_display"+"\"");
//                        if(null!=splitHiddenList&&splitHiddenList.contains(split[index])){
//                            columnsSB.append("checked=\"checked\"");
//                        }
//                        columnsSB.append("></div>");
//                        columnsSB.append(" </div></td>");
//                        columnsSB.append(" <td><div class=\"formControls\"><span class=\"select-box\"><select id=\""+split[index]+"_format\" name=\""+split[index]+"_format\" class=\"select\">");
//                        for(int n=0;n<formatterList.size();n++){
//                            columnsSB.append("<option value=\""+formatterList.get(n).getConstantValue()+"\"");
//                            if(getTypeFormatter(all,split[index]).equals(formatterList.get(n).getConstantValue())){
//                                columnsSB.append(" selected ");
//                            }
//                            columnsSB.append(">"+formatterList.get(n).getConstantValueDesc()+"</option>");
//                        }
//                        columnsSB.append("  </select></span></div></td>");
//
//                        columnsSB.append(" <td><div class=\"formControls\"><span class=\"select-box\"><select id=\""+split[index]+"_typeConstraint\" name=\""+split[index]+"_typeConstraint\" class=\"select\">");
//                        for(int m=0;m<constantsList.size();m++){
//                            columnsSB.append("<option value=\""+constantsList.get(m).getConstantValue()+"\"");
//                            if(getTypeConstraint(all,split[index]).equals(constantsList.get(m).getConstantValue())){
//                                columnsSB.append(" selected ");
//                            }
//                            columnsSB.append(">"+constantsList.get(m).getConstantValueDesc()+"</option>");
//                        }
//                        columnsSB.append("</select></span></div></td>");
//                    }else if(index==split.length){
//                        columnsSB.append(" <th> </th><td><div class=\"formControls\"></div></td><td><div class=\"formControls\"></div></td>");
//                        columnsSB.append(" <td><div class=\"formControls\"></div></td><td></td><td><div class=\"formControls\"></div></td>");
//                    }
                }
                columnsSB.append("</tr>");
            }

            modelAndView.addObject("entity", byId);
            modelAndView.addObject("code", columnsSB.toString());
            viewName = "config/column-set";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    @RequestMapping("/config-global-set")
    public ModelAndView configGlobalList(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            List<SystemGlobalEntity> all = systemGlobalService.findAll();
            SystemGlobalEntity systemGlobalEntity = null;
            if(all.size()!=1){
                systemGlobalEntity = new SystemGlobalEntity();
            }else{
                systemGlobalEntity = all.get(0);
            }
            modelAndView.addObject("entity", systemGlobalEntity);
            viewName = "config/global-set";
        }
          modelAndView.setViewName(viewName);
        return modelAndView;
    }
    //----------------------------------------------------------------------

    private String getTypeFormatter(List<SystemFieldEntity> all,String key){
        String result = "";
        for(SystemFieldEntity systemFieldEntity :all){
            if(systemFieldEntity.getFieldEn().equals(key)){
                result = systemFieldEntity.getIsFormatter();
                break;
            }
        }
        return result;
    }

    private String getTypeConstraint(List<SystemFieldEntity> all,String key){
        String result = "";
        for(SystemFieldEntity systemFieldEntity :all){
            if(systemFieldEntity.getFieldEn().equals(key)){
                result = systemFieldEntity.getTypeConstraint();
                break;
            }
        }
        return result;
    }
    private String getCN(List<SystemFieldEntity> all,String key){
        String cn = "";
        for(SystemFieldEntity systemFieldEntity :all){
            if(systemFieldEntity.getFieldEn().equals(key)){
                cn = systemFieldEntity.getFieldCn();
                break;
            }
        }
        return cn;
    }
    private String getExport(List<SystemFieldEntity> all,String key){
        String cn = "";
        for(SystemFieldEntity systemFieldEntity :all){
            if(systemFieldEntity.getIsExport()!=null&&systemFieldEntity.getFieldEn().equals(key)){
                cn = systemFieldEntity.getIsExport();
                break;
            }else{
                cn = "";
            }
        }
        return cn;
    }
    private String getMerge(List<SystemFieldEntity> all,String key){
        String cn = "";
        for(SystemFieldEntity systemFieldEntity :all){
            if(systemFieldEntity.getIsMerge()!=null&&systemFieldEntity.getFieldEn().equals(key)){
                cn = systemFieldEntity.getIsMerge();
                break;
            }else{
                cn = "";
            }
        }
        return cn;
    }
}
